package com.xjnt.frameworks.interceptor;

import java.lang.reflect.Field;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xjnt.frameworks.annotation.AutoInject;
import com.xjnt.frameworks.core.BaseService;
import com.xjnt.frameworks.plugin.service.ServiceKit;
import com.xjnt.frameworks.utils.ReflectKit;

/**
 * 注入拦截器
 * @author caoyong
 *
 */
public class InjectInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation invoc) {
		if (invoc.isActionInvocation()) {
			inject(invoc.getController());
		}
		invoc.invoke();
	}

	private void inject(Controller c) {
		if (null != c) {
			Field[] fields = c.getClass().getDeclaredFields();
			for (Field field : fields) {
				AutoInject aInject = field.getAnnotation(AutoInject.class);
				if (null == aInject) {
					continue;
				}
				Class<?> clazz = field.getType();
				if (clazz.getSuperclass().equals(BaseService.class)) {
					if ( StrKit.notBlank(aInject.value()) ) {
						ReflectKit.on(c).set(field.getName(), c.enhance(ServiceKit.getService(aInject.value()), Tx.class));
					} else {
						String serviceName = StrKit.firstCharToLowerCase(clazz.getSimpleName());
						ReflectKit.on(c).set(field.getName(), c.enhance(ServiceKit.getService(serviceName), Tx.class));
					}
				}
			}
		}
	}

}
